/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.leadiv.cards;

import com.leadiv.cards.Rook.RookPlayer;
import java.util.Iterator;
import java.util.Vector;

/**
 *
 * @author pborrego
 */
public class Bidding {
    public static int PASS = 0;
    private int winner;
    private int bid;
    private final int maxbid;
    private final int minbid;
    private final int increment;
    private Vector<Integer> bids;
    private int currentBidder;

    public Bidding(int max, int min, int playerCnt, int firstBidder)
    {
        this.increment = 5;
        this.maxbid = max;
        this.minbid = min;
        this.winner = firstBidder;
        this.bid = this.minbid - 1;
        this.bids = new Vector<Integer>(playerCnt);
        this.currentBidder = firstBidder;

        for(int i=0; i<playerCnt; i++)
            this.bids.add(new Integer(-1));
    }

    public void printBidInfo()
    {
        Iterator<Integer> iter = this.bids.iterator();

        System.out.println("Winner Index: " + this.winner);
        System.out.println("Winning Bid: " + this.bid);
        System.out.println("Current Bidder: " + this.currentBidder);

        while(iter.hasNext())
        {
            System.out.println("Bid: " + iter.next());
        }
    }

    public int getWinnerIndex()
    {
        return this.winner;
    }

    public RookPlayer getWinner(Vector<RookPlayer> players)
    {
        return players.get(this.winner);
    }
    
    public int getBid()
    {
        return this.bid;
    }

    public int getCurrentBidderIndex()
    {
        return this.currentBidder;
    }

    public RookPlayer getCurrentBidder(Vector<RookPlayer> players)
    {
        return players.get(this.currentBidder);
    }

    public boolean doneBidding()
    {
        int i = 0;
        int playerCnt = this.bids.size();
        int passCnt = 0;

        for(; i < playerCnt; i++)
            if(this.bids.get(i).intValue() == Bidding.PASS) passCnt++;

        return (passCnt + 1) == playerCnt;
    }

    public void bid(int bid) throws InvalidBidException
    {
        int playerCnt = this.bids.size();

        if(bid < this.minbid || bid > this.maxbid || bid % this.increment != 0)
            throw new InvalidBidException(bid);

        if(bid > this.bid)
        {
            this.bid = bid;
            bids.set(this.currentBidder, new Integer(bid));
            this.winner = this.currentBidder;
        }
        else
        {
            bids.set(this.currentBidder, new Integer(Bidding.PASS));
        }

        this.currentBidder = (this.currentBidder + 1) % playerCnt;
        while(this.bids.get(this.currentBidder).intValue() == Bidding.PASS)
            this.currentBidder = (this.currentBidder + 1) % playerCnt;
    }
}
